package com.zhiche.lisa.bms.service.fee.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zhiche.lisa.bms.dao.mapper.fee.FeeRewardMapper;
import com.zhiche.lisa.bms.dao.model.fee.FeeReward;
import com.zhiche.lisa.bms.dao.model.pay.PayApplyDtlFund;
import com.zhiche.lisa.bms.pojo.dto.driver.DriverDTO;
import com.zhiche.lisa.bms.pojo.dto.fee.FeeAssessmentAndRewardDTO;
import com.zhiche.lisa.bms.pojo.dto.util.*;
import com.zhiche.lisa.bms.pojo.vo.fee.FeeRewardConventVO;
import com.zhiche.lisa.bms.pojo.vo.fee.FeeRewardVO;
import com.zhiche.lisa.bms.service.fee.FeeRewardService;
import com.zhiche.lisa.bms.service.pay.PayApplyDtlFundService;
import com.zhiche.lisa.bms.service.utils.LspUtil;
import com.zhiche.lisa.bms.service.utils.OtmUtil;
import com.zhiche.lisa.bms.service.utils.common.AccountBindUtil;
import com.zhiche.lisa.bms.utils.ToolCommonUtils;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 奖励费用 服务实现类
 * </p>
 *
 * @author liuanshun
 * @since 2019-01-29
 */
@Service
@Slf4j
public class FeeRewardServiceImpl extends ServiceImpl<FeeRewardMapper, FeeReward> implements FeeRewardService {
    @Autowired
    private LspUtil lspUtil;
    @Autowired
    private OtmUtil otmUtil;

    @Autowired
    private PayApplyDtlFundService payApplyDtlFundService;

    private EntityWrapper<FeeReward> bindFeeRewardWrapper(Map<String, Object> condition) {
        EntityWrapper<FeeReward> feeRewardEntityWrapper = new EntityWrapper<>();
        if (!CollectionUtils.isEmpty(condition)) {
            for (Map.Entry<String, Object> item :
                    condition.entrySet()) {
                if (!StringUtils.isEmpty(item.getValue())) {
                    if ("redCode".equals(item.getKey())) {
                        feeRewardEntityWrapper.eq("red_code", item.getValue().toString());
                        continue;
                    }
                    if ("redCodes".equals(item.getKey())) {
                        feeRewardEntityWrapper.in("red_code", (ArrayList) item.getValue());
                        continue;
                    }
                    if ("isPut".equals(item.getKey())) {
                        feeRewardEntityWrapper.eq("is_put", item.getValue().toString());
                        continue;
                    }
                    if ("isHang".equals(item.getKey())) {
                        feeRewardEntityWrapper.eq("is_hang", item.getValue().toString());
                        continue;
                    }
                    if ("isBalance".equals(item.getKey())) {
                        feeRewardEntityWrapper.gt("balance_sum", BigDecimal.ZERO);
                        continue;
                    }
                    if ("lspId".equals(item.getKey())) {
                        feeRewardEntityWrapper.eq("lsp_id", item.getValue().toString());
                        continue;
                    }
                    if ("fleetId".equals(item.getKey())) {
                        feeRewardEntityWrapper.eq("fleet_id", item.getValue().toString());
                        continue;
                    }
                    if ("redMonth".equals(item.getKey())) {
                        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM");
                        Date firstDayOfMonth = ToolCommonUtils.getFirstDayOfMonth(format.parseDateTime(item.getValue().toString()).toDate());
                        feeRewardEntityWrapper.eq("red_month", firstDayOfMonth);
                        continue;
                    }
                    // 承运类型
                    if ("fleetTeye".equals(item.getKey())) {
                        feeRewardEntityWrapper.eq("fleet_teye", item.getValue().toString());
                        continue;
                    }
                    // 承运人
                    if ("fleetStatus".equals(item.getKey())) {
                        feeRewardEntityWrapper.like("fleet_status", item.getValue().toString());
                        continue;
                    }
                    // 承运商名称
                    if ("lspName".equals(item.getKey())) {
                        feeRewardEntityWrapper.like("lsp_name", item.getValue().toString());
                        continue;
                    }
                    // 创建人名称
                    if ("createUsername".equals(item.getKey()) && !StringUtils.isEmpty(item.getValue())) {
                        feeRewardEntityWrapper.like("create_username", item.getValue().toString());
                        continue;
                    }
                    // 创建时间
                    if ("createTimeStart".equals(item.getKey()) && !StringUtils.isEmpty(item.getValue())) {
                        feeRewardEntityWrapper.ge("gmt_create", item.getValue());
                        continue;
                    }
                    // 创建时间
                    if ("createTimeEnd".equals(item.getKey()) && !StringUtils.isEmpty(item.getValue())) {
                        feeRewardEntityWrapper.le("gmt_create", item.getValue());
                        continue;
                    }
                    // 奖项月
                    if ("redMonthStart".equals(item.getKey()) && !StringUtils.isEmpty(item.getValue())) {
                        Date redMonthStart = ToolCommonUtils.getDateByStr(item.getValue().toString(), ToolCommonUtils.yyyyMM);
                        feeRewardEntityWrapper.ge("red_month", ToolCommonUtils.getFirstDayOfMonth(redMonthStart));
                        continue;
                    }
                    // 奖项月
                    if ("redMonthEnd".equals(item.getKey()) && !StringUtils.isEmpty(item.getValue())) {
                        Date redMonthEnd = ToolCommonUtils.getDateByStr(item.getValue().toString(), ToolCommonUtils.yyyyMM);
                        feeRewardEntityWrapper.le("red_month", ToolCommonUtils.getLastDayOfMonth(redMonthEnd));
                        continue;
                    }
                    // 关闭状态
                    if ("closeFlag".equals(item.getKey()) && !StringUtils.isEmpty(item.getValue())) {
                        feeRewardEntityWrapper.like("close_flag", item.getValue().toString());
                        continue;
                    }
                }
            }
        }
        return feeRewardEntityWrapper;
    }

    /**
     * 根据查询条件获取奖励费用数据
     *
     * @param condition
     * @return
     */
    @Override
    public List<FeeReward> selectFeeRewardList(Map<String, Object> condition) {
        EntityWrapper<FeeReward> feeRewardEntityWrapper = this.bindFeeRewardWrapper(condition);
        feeRewardEntityWrapper.orderBy("id desc");
        return this.selectList(feeRewardEntityWrapper);
    }

    /**
     * 根据查询条件获取奖励费用分页数据
     *
     * @param pageParam
     * @return
     */
    @Override
    public Page<FeeRewardConventVO> selectFeeRewardPage(Page<FeeReward> pageParam) {
        Page<FeeRewardConventVO> feeRewardConventVOPage = new Page<>();
        //Select
        EntityWrapper<FeeReward> feeRewardEntityWrapper = this.bindFeeRewardWrapper(pageParam.getCondition());
        pageParam.setCondition(new HashMap<>());
        feeRewardEntityWrapper.orderBy("id desc");
        Page<FeeReward> feeRewardPage = this.selectPage(pageParam, feeRewardEntityWrapper);
        //Copy
        BeanUtils.copyProperties(feeRewardPage, feeRewardConventVOPage);
        List<FeeRewardConventVO> feeRewardConventVOS = new ArrayList<>();
        for (FeeReward feeReward : feeRewardPage.getRecords()) {
            FeeRewardConventVO feeRewardConventVO = new FeeRewardConventVO();
            BeanUtils.copyProperties(feeReward, feeRewardConventVO);
            feeRewardConventVOS.add(feeRewardConventVO);
        }
        feeRewardConventVOPage.setRecords(feeRewardConventVOS);

        return feeRewardConventVOPage;
    }

    /**
     * 批量新增
     *
     * @param insertData
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void insertBatchFeeReward(List<FeeReward> insertData) {
        if (!CollectionUtils.isEmpty(insertData)) {
            AccountBindUtil<FeeReward> feeRewardAccountBindUtil = new AccountBindUtil<>();
            for (FeeReward feeReward : insertData) {
                if (feeReward.getIsHang() == null) {
                    feeReward.setIsHang(0);
                }
                if (feeReward.getIsCreate() == null) {
                    feeReward.setIsCreate(0);
                }
                if (feeReward.getBalanceSum() == null) {
                    feeReward.setBalanceSum(feeReward.getRedSum());
                }
                if (feeReward.getInvoiceType() == null) {
                    feeReward.setInvoiceType(1);
                }
                feeRewardAccountBindUtil.bindCreatorAndTenantId(feeReward, true);
            }
            this.insertBatch(insertData);
        }
    }

    /**
     * 批量审核
     *
     * @param ids
     * @param token
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void examine(List<Long> ids, String token) {
        try {
            List<FeeReward> feeRewards = this.selectBatchIds(ids);
            if (!CollectionUtils.isEmpty(feeRewards)) {
                for (FeeReward feeReward : feeRewards) {
                    if (feeReward.getIsHang() != 0) {
                        throw new BaseException("该奖赏项已挂起");
                    }
                }
                bindFleetIdByStatus(feeRewards, token);
                for (FeeReward feeReward : feeRewards) {
                    feeReward.setIsCreate(1);
                    if (feeReward.getFleetId() == null) {
                        throw new BaseException("审核失败，所选无法匹配承运人" + feeReward.getFleetStatus());
                    }
                }
                this.updateBatchById(feeRewards);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("批量审核异常");
        }
    }

    /**
     * 挂起
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void hang(List<Long> ids) {
        try {
            List<FeeReward> feeRewards = this.selectBatchIds(ids);
            if (!CollectionUtils.isEmpty(feeRewards)) {
                List<AssessRedDTO> dtoList = Lists.newArrayList();
                for (FeeReward feeReward : feeRewards) {
                    if (feeReward.getIsCreate() != 0 && feeReward.getIsPut() != 0) {
                        AssessRedDTO assessRedDTO = rewardConventServiceBmsDto(feeReward);
                        assessRedDTO.setDelFlag(1);
                        dtoList.add(assessRedDTO);
                    }
                    feeReward.setIsHang(1);
                }
                if (!CollectionUtils.isEmpty(dtoList)) {
                    BmsServiceResult bmsServiceResult = otmUtil.delFlagURL(dtoList);
                    if (bmsServiceResult == null) {
                        throw new BaseException("同步BMS未响应");
                    } else if (!bmsServiceResult.isSuccess()) {
                        throw new BaseException("同步BMS：" + bmsServiceResult.getMessage());
                    }
                }
                this.updateBatchById(feeRewards);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("批量挂起异常");
        }
    }

    /**
     * 取消挂起
     *
     * @param ids
     */
    @Override
    public void unhang(List<Long> ids) {
        try {
            List<FeeReward> feeRewards = this.selectBatchIds(ids);
            if (!CollectionUtils.isEmpty(feeRewards)) {
                for (FeeReward feeReward :
                        feeRewards) {
                    feeReward.setIsHang(0);
                }
                this.updateBatchById(feeRewards);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("批量恢复异常");
        }
    }

    /**
     * 删除
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void delete(List<Long> ids) {
        try {
            List<FeeReward> feeRewards = this.selectBatchIds(ids);
            if (!CollectionUtils.isEmpty(feeRewards)) {
                for (FeeReward feeReward :
                        feeRewards) {
                    if (feeReward.getIsCreate() != 0) {
                        if (Objects.deepEquals(new Integer(0), feeReward.getIsHang())) {
                            throw new BaseException("请在挂起后删除");
                        }
                    }
                }
                this.deleteBatchIds(ids);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("批量删除异常");
        }
    }

    /**
     * 奖励单发布
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void release(List<Long> ids) {
        try {
            List<FeeReward> feeRewards = this.selectBatchIds(ids);
            JwtAccountVO account = AccountUtil.getAccountInfoFromSecurityContext();
            if (!CollectionUtils.isEmpty(feeRewards)) {
                List<AssessRedDTO> dtoList = Lists.newArrayList();
                for (FeeReward feeReward : feeRewards) {
                    if (feeReward.getIsCreate() != 0) {
                        AssessRedDTO assessRedDTO = rewardConventServiceBmsDto(feeReward);
                        dtoList.add(assessRedDTO);
                        //BmsServiceResult bmsServiceResult = otmUtil.syncRedURL(assessRedDTO);
                        //if (bmsServiceResult == null) {
                        //	throw new BaseException("同步BMS未响应");
                        //} else if (!bmsServiceResult.isSuccess()) {
                        //	throw new BaseException("同步BMS：" + bmsServiceResult.getMessage());
                        //}
                        feeReward.setPutUsername(account.getUsername());
                        feeReward.setIsPut(1);
                    } else {
                        throw new BaseException("未审核");
                    }
                }
                BmsServiceResult bmsServiceResult = otmUtil.syncRedURL(dtoList);
                if (bmsServiceResult == null) {
                    throw new BaseException("同步BMS未响应");
                } else if (!bmsServiceResult.isSuccess()) {
                    throw new BaseException("同步BMS：" + bmsServiceResult.getMessage());
                }
                this.updateBatchById(feeRewards);
            }
        } catch (BaseException e) {
            log.error("FeeRewardServiceImpl.release error: {}", e);
            throw e;
        } catch (Exception e) {
            log.error("FeeRewardServiceImpl.release error: {}", e);
            throw new BaseException("批量发布异常");
        }
    }

    /**
     * 根据支付申请单号获取奖励单
     *
     * @param payApplyId
     * @return
     */
    @Override
    public List<FeeReward> getFeeRewardListByPayId(Long payApplyId) {
        if (payApplyId != null) {
            List<PayApplyDtlFund> payApplyDtlFundsList = payApplyDtlFundService.queryPayApplyDtlFundList(payApplyId);
            if (payApplyDtlFundsList.isEmpty()) {
                return null;
            }
            List<Long> billIds = Lists.newArrayList();
            payApplyDtlFundsList.forEach(payApplyDtlBill -> {
                if (!ObjectUtils.isEmpty(payApplyDtlBill.getBilId())) {
                    billIds.add(payApplyDtlBill.getBilId());
                }
            });
            if (billIds.isEmpty()) {
                return null;
            }
            EntityWrapper ew = new EntityWrapper<>();
            ew.in("id", billIds);
            return this.selectList(ew);
        }
        return null;
    }

    /**
     * 根据支付申请单号获取奖励单
     *
     * @param payApplyId
     * @return
     */
    @Override
    public List<FeeRewardVO> getFeeRewardVOListByPayId(Long payApplyId) {
        if (payApplyId != null) {
            List<PayApplyDtlFund> payApplyDtlFundsList = payApplyDtlFundService.queryPayApplyDtlFundList(payApplyId);
            if (CollectionUtils.isEmpty(payApplyDtlFundsList)) {
                return null;
            }
            List<Long> billIds = Lists.newArrayList();
            payApplyDtlFundsList.forEach(payApplyDtlBill -> {
                if (!ObjectUtils.isEmpty(payApplyDtlBill.getBilId())) {
                    billIds.add(payApplyDtlBill.getBilId());
                }
            });
            if (billIds.isEmpty()) {
                return null;
            }
            EntityWrapper<FeeReward> ew = new EntityWrapper<>();
            ew.in("id", billIds);
            List<FeeReward> feeRewardList = this.selectList(ew);
            List<FeeRewardVO> voList = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(feeRewardList)) {
                feeRewardList.forEach(fee -> {
                    FeeRewardVO feeVo = new FeeRewardVO();
                    for (PayApplyDtlFund payApplyDtlFund : payApplyDtlFundsList) {
                        if (fee.getId().equals(payApplyDtlFund.getBilId())) {
                            BeanUtils.copyProperties(fee, feeVo);
                            feeVo.setSingleWithHoldSum(payApplyDtlFund.getArSum());
                            voList.add(feeVo);
                            continue;
                        }
                    }
                });
            }
            return voList;
        }
        return null;
    }

    /**
     * 根据单号查询
     *
     * @param codes
     * @return
     */
    @Override
    public List<FeeReward> selectFeeRewardListByCodes(Collection<String> codes) {
        if (!CollectionUtils.isEmpty(codes)) {
            EntityWrapper<FeeReward> ew = new EntityWrapper<>();
            ew.in("red_code", codes);
            return baseMapper.selectListNoTenant(ew);
        }
        return null;
    }

    /**
     * 关闭奖励单
     *
     * @param idList
     * @param reason
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public List<String> closeReward(List<Long> idList, String reason) {

        List<String> resultMessageList = Lists.newArrayList();

        List<FeeReward> feeRewardList = this.selectBatchIds(idList);
        List<FeeReward> closeBmsDataList = Lists.newArrayList();
        List<FeeReward> updateBmsDataList = Lists.newArrayList();


        List<FeeReward> notPutRewardList = Lists.newArrayList();

        if (!CollectionUtils.isEmpty(feeRewardList)) {
            feeRewardList.stream()
                    .forEach(feeReward -> {
                        if (Objects.nonNull(feeReward.getIsPut()) && Integer.valueOf(1).equals(feeReward.getIsPut())) {

                            if (Objects.isNull(feeReward.getPerformSum())) {
                                feeReward.setPerformSum(BigDecimal.ZERO);
                            }
                            if (Objects.isNull(feeReward.getBmsSum())) {
                                feeReward.setBmsSum(BigDecimal.ZERO);
                            }
                            // 判断执行金额
                            if (Objects.isNull(feeReward.getPerformSum())) {
                                // 执行金额 = 0 是关闭
                                closeBmsDataList.add(feeReward);
                            } else {
                                if (BigDecimal.ZERO.compareTo(feeReward.getPerformSum()) == 0 && BigDecimal.ZERO.compareTo(feeReward.getBmsSum()) == 0) {
                                    // 执行金额 = 0 是关闭
                                    closeBmsDataList.add(feeReward);
                                } else {
                                    // 执行金额 != 0 是更新
                                    updateBmsDataList.add(feeReward);
                                }
                            }
                        } else {
                            notPutRewardList.add(feeReward);
                        }
                    });
        }

        List<BmsServiceData> bmsServiceDataList = Lists.newArrayList();

        //TODO 调用bms接口
        if (!CollectionUtils.isEmpty(closeBmsDataList)) {
            // 推送bms关闭
            List<BmsServiceData> closeDataList = this.bmsCloseReward(closeBmsDataList);
            if (!CollectionUtils.isEmpty(closeDataList)) {
                bmsServiceDataList.addAll(closeDataList);
            }
        }
        if (!CollectionUtils.isEmpty(updateBmsDataList)) {
            // 推送bms更新
            List<BmsServiceData> updateDataList = this.bmsUpdateRewward(updateBmsDataList);
            if (!CollectionUtils.isEmpty(updateDataList)) {
                bmsServiceDataList.addAll(updateDataList);
            }
        }
        if (!CollectionUtils.isEmpty(bmsServiceDataList)) {
            List<String> codeList = Lists.newArrayList();
            bmsServiceDataList.forEach(resultData -> {
                if (resultData.isDealFlag()) {
                    codeList.add(resultData.getAssessCode());
                } else {
                    resultMessageList.add("单号:" + resultData.getAssessCode() + ":" + resultData.getDealMessage());
                }
            });
            EntityWrapper<FeeReward> ew = new EntityWrapper<>();
            ew.in("red_code", codeList);
            FeeReward updateReward = new FeeReward();
            updateReward.setCloseFlag(1);
            updateReward.setCloseReason(reason);
            // 同时挂起
            updateReward.setIsHang(1);
            // 更新数据
            this.update(updateReward, ew);
        }
        if (!CollectionUtils.isEmpty(notPutRewardList)) {
            notPutRewardList.forEach(feeReward -> {
                feeReward.setCloseFlag(1);
                feeReward.setCloseReason(reason);
                // 同时挂起
                feeReward.setIsHang(1);
            });
            this.updateBatchById(notPutRewardList);
        }
        return resultMessageList;

    }

    /**
     * 更新bms奖励单
     *
     * @param updateBmsDataList
     */
    private List<BmsServiceData> bmsUpdateRewward(List<FeeReward> updateBmsDataList) {
        List<FeeAssessmentAndRewardDTO> dtoList = Lists.newArrayList();
        updateBmsDataList.forEach(bmsData -> {
            FeeAssessmentAndRewardDTO dto = otmUtil.packageParamJson(bmsData.getRedCode(),
                    1, bmsData.getPerformSum(), bmsData.getBmsSum());
            dtoList.add(dto);
        });
        BmsServiceResult bmsServiceResult = otmUtil.assessmentAndRewardUpdate(dtoList);
        if (Objects.isNull(bmsServiceResult)) {
            throw new BaseException("bms系统没有返回数据");
        }
        if (!bmsServiceResult.isSuccess()) {
            throw new BaseException(bmsServiceResult.getMessage());
        }
        if (!StringUtils.isEmpty(bmsServiceResult.getData())) {
            return JSONArray.parseArray(bmsServiceResult.getData(), BmsServiceData.class);
        }
        return null;
    }

    /**
     * 关闭
     *
     * @param closeBmsDataList
     */
    private List<BmsServiceData> bmsCloseReward(List<FeeReward> closeBmsDataList) {
        List<AssessRedDTO> dtoList = Lists.newArrayList();
        closeBmsDataList.forEach(bmsData -> {
            AssessRedDTO assessRedDTO = new AssessRedDTO();
            assessRedDTO.setAssessCode(bmsData.getRedCode());
            assessRedDTO.setDelFlag(1);
            dtoList.add(assessRedDTO);
        });
        BmsServiceResult bmsServiceResult = otmUtil.delFlagURL(dtoList);
        if (Objects.isNull(bmsServiceResult)) {
            throw new BaseException("bms系统没有返回数据");
        }
        if (!bmsServiceResult.isSuccess()) {
            throw new BaseException(bmsServiceResult.getMessage());
        }
        if (!StringUtils.isEmpty(bmsServiceResult.getData())) {
            return JSONArray.parseArray(bmsServiceResult.getData(), BmsServiceData.class);
        }
        return null;
    }

    /**
     * 封装传送bms的对象
     *
     * @param feeReward
     * @return
     */
    private AssessRedDTO rewardConventServiceBmsDto(FeeReward feeReward) {
        AssessRedDTO assessRedDTO = new AssessRedDTO();
        assessRedDTO.setAssessCode(feeReward.getRedCode());
        assessRedDTO.setAssessMoney(feeReward.getRedSum());
        assessRedDTO.setAssessMonth(feeReward.getRedMonth());
        assessRedDTO.setAssessName(feeReward.getRedItem());
        assessRedDTO.setAssessReason(feeReward.getRedCause());
        assessRedDTO.setAssessWay(feeReward.getRedWay());
        assessRedDTO.setCreateTime(feeReward.getGmtCreate());
        assessRedDTO.setShipperId(feeReward.getLspId());
        assessRedDTO.setShipperName(feeReward.getLspName());
        assessRedDTO.setInvoiceStatus(feeReward.getInvoiceType());
        return assessRedDTO;
    }

    private void bindFleetIdByStatus(List<FeeReward> feeRewards, String token) {
        List<LspInfoDTO> fleetType1List = new ArrayList<>(); // lspName
        List<LspFleetDTO> fleetType2List = new ArrayList<>(); // fleetName
        List<DriverDTO> fleetType3List = new ArrayList<>(); // driverName

        for (FeeReward feeReward :
                feeRewards) {
            if (feeReward.getFleetId() != null) {
                throw new BaseException("请指定未审核/无承运人id的数据");
            }
            if (feeReward.getLspName() != null) {
                LspInfoDTO lspInfoDTO = new LspInfoDTO();
                lspInfoDTO.setName(feeReward.getLspName());
                fleetType1List.add(lspInfoDTO);
            }

            if ("10".equals(feeReward.getFleetTeye())) {
                LspInfoDTO lspInfoDTO = new LspInfoDTO();
                lspInfoDTO.setName(feeReward.getFleetStatus());
                fleetType1List.add(lspInfoDTO);
            } else if ("20".equals(feeReward.getFleetTeye())) {
                LspFleetDTO lspFleetDTO = new LspFleetDTO();
                lspFleetDTO.setFleetName(feeReward.getFleetStatus());
                fleetType2List.add(lspFleetDTO);
            } else if ("30".equals(feeReward.getFleetTeye())) {
                DriverDTO driverDTO = new DriverDTO();
                driverDTO.setName(feeReward.getFleetStatus());
                driverDTO.setSendCarPass(feeReward.getSendCarPass());
                driverDTO.setMobile(feeReward.getDriverPhone());
                fleetType3List.add(driverDTO);
            } else {
                new BaseException("承运人类型无法识别");
            }
        }
        List<LspInfoDTO> lspInfoList = lspUtil.getLspInfoAll(fleetType1List, token);
        Map<String, LspInfoDTO> nameAndLspMap = new HashMap<>();
        if (!lspInfoList.isEmpty()) {
            lspInfoList.forEach(lspInfoDTO -> {
                nameAndLspMap.put(lspInfoDTO.getName(), lspInfoDTO);
            });
        }
        List<LspFleetDTO> fleetList = lspUtil.getFleetAll(fleetType2List, token);
        Map<String, LspFleetDTO> nameAndFleetMap = new HashMap<>();
        if (!fleetList.isEmpty()) {
            fleetList.forEach(fleetDTO -> {
                nameAndFleetMap.put(fleetDTO.getFleetName(), fleetDTO);
            });
        }
        List<DriverDTO> driverList = lspUtil.getDriverAll(fleetType3List, token);
        Map<String, DriverDTO> nameAndDriverMap = new HashMap<>();
        if (!driverList.isEmpty()) {
            driverList.forEach(driverDTO -> {
                nameAndDriverMap.put(driverDTO.getName(), driverDTO);
            });
        }
        for (FeeReward feeReward : feeRewards) {
            boolean haveLsp = false;
            if (feeReward.getLspName() != null) {
                haveLsp = true;
            }

            String itemLspName = null;
            Long itemLspId = null;

            if ("10".equals(feeReward.getFleetTeye())) {
                if (nameAndLspMap.containsKey(feeReward.getFleetStatus())) {
                    LspInfoDTO lspInfoDTO = nameAndLspMap.get(feeReward.getFleetStatus());
                    if (lspInfoDTO != null) {
                        feeReward.setFleetId(lspInfoDTO.getId());
                        itemLspId = lspInfoDTO.getId();
                        itemLspName = lspInfoDTO.getName();
                    }
                }
            } else if ("20".equals(feeReward.getFleetTeye())) {
                if (nameAndFleetMap.containsKey(feeReward.getFleetStatus())) {
                    LspFleetDTO lspFleetDTO = nameAndFleetMap.get(feeReward.getFleetStatus());
                    if (lspFleetDTO != null) {
                        feeReward.setFleetId(lspFleetDTO.getId());
                        itemLspId = lspFleetDTO.getLspId();
                        itemLspName = lspFleetDTO.getLspName();
                    }
                }
            } else if ("30".equals(feeReward.getFleetTeye())) {
                if (nameAndDriverMap.containsKey(feeReward.getFleetStatus())) {
                    DriverDTO driverDTO = nameAndDriverMap.get(feeReward.getFleetStatus());
                    if (driverDTO != null) {
                        feeReward.setFleetId(driverDTO.getId());
                        feeReward.setDriverPhone(driverDTO.getMobile());
                        itemLspId = driverDTO.getLspId();
                        itemLspName = driverDTO.getLspName();
                    }
                }
            }
            if (haveLsp) {
                if (nameAndLspMap.containsKey(feeReward.getLspName())) {
                    LspInfoDTO lspInfoDTO = nameAndLspMap.get(feeReward.getLspName());
                    if (lspInfoDTO != null) {
                        feeReward.setLspName(lspInfoDTO.getName());
                        feeReward.setLspId(lspInfoDTO.getId());
                        feeReward.setTenantId(lspInfoDTO.getTenantId());
                    }
                }
            } else {
                feeReward.setLspId(itemLspId);
                feeReward.setLspName(itemLspName);
            }
        }
    }
}
